<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="17"
      :excludeValues="['startTime_begin', 'startTime_end']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processInstanceId" label="流程实例ID">
          <FIInput v-model="state.query.processInstanceId" clearable />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processKey" label="流程编码">
          <FIInput v-model="state.query.processKey" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processName" label="流程名称">
          <FIInput v-model="state.query.processName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="state" label="任务执行状态">
          <FISelect
            v-model="state.query.state"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'succeed', label: '成功' },
              { value: 'failed', label: '失败' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="sequenceId" label="流程流水号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="processInstanceId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleActionClick"
    >
      <!-- 自定义列 moduleEname1 -->
      <!-- <template #manage="{ scope }">
        <FIButton border size="small">流程跟踪</FIButton>
      </template> -->
      <template #headerBtn>
        <FIPopconfirmBtn
          title="您确定要重新调用所选数据吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="重新调用"
          :btn-binds="{ id: 'reInvoke', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleRecall"
        />
        <!-- <el-button class="margin-left12" :loading="exportLoading" type="primary" @click="exportClick">导出</el-button> -->
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiQueryAllProcesses, apiQueryUser, apiQueryTask, apiQueryDept, apiQueryApp } from '@/api/modules/EWPT.js'
import { apiRequestPost } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, useRouteNavigation } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
const processDefKeyKeyWord = ref('')
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'ProcInst'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    processInstanceId: '', // 流程实例ID
    processKey: '', // 流程编码
    processName: '', // 流程名称
    state: '', // 任务执行状态
    sequenceId: '', // 流程流水号
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '流程流水号',
    prop: 'sequenceId',
    align: 'center',
    width: '120',
  },
  {
    label: 'jobID',
    prop: 'jobId',
    align: 'center',
    width: '220',
  },
  {
    label: '流程实例ID',
    prop: 'processInstanceId',
    align: 'center',
    width: '220',
  },
  {
    label: '流程编码',
    prop: 'processKey',
    align: 'center',
    width: '150',
  },
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    width: '150',
  },
  {
    label: '活动编码',
    prop: 'nodeKey',
    align: 'center',
    width: '150',
  },
  {
    label: '活动名称',
    prop: 'nodeName',
    align: 'center',
    width: '150',
  },
  {
    label: '状态',
    prop: 'state',
    align: 'center',
    width: '150',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'wait', label: '等待执行' },
        { value: 'succeed', label: '成功' },
        { value: 'failed', label: '失败' },
      ],
    },
  },
  {
    label: '服务执行信息',
    prop: 'failureReason',
    align: 'center',
    width: '150',
  },
  // {
  //   label: '管理',
  //   prop: 'manage',
  //   align: 'center',
  //   width: '120',
  // },
  {
    label: '第一次调用时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '最后一次执行时间',
    prop: 'recReviseTime',
    align: 'center',
    minWidth: '160',
    editType: 'date-picker',
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'trace', type: '流程跟踪' }],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}

// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
// 重新调用
const handleRecall = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请至少选择一条数据！')
    return
  }
  let ids = []
  let flag = false
  if (Array.isArray(checkedRows.value)) {
    for (let i = 0; i < checkedRows.value.length; i++) {
      if (checkedRows.value[i].state == 'succeed') {
        flag = true
        break
      } else {
        ids.push(checkedRows.value[i].jobId)
      }
    }
  }
  if (flag == true) {
    useMessage().warning('失败的任务才能重新调用,请重新选择')
    return
  }
  isTableLoading.value = true
  const apiUrl = proxy.$Button_api('reInvoke', route.name)
  apiRequestPost(apiUrl, { jobIdList: ids })
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success('调用成功')
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const { navigateToPage } = useRouteNavigation()
// 操作按钮回调
const handleActionClick = (item, rowData) => {
  // openUrlFn(item.id, rowData)
  if (item.id == 'trace') {
    navigateToPage(item.id, rowData)
    // openUrlFn('trace', rowData)
  }
}
//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  apiRequestPost('/bpm-service/ServiceRetry/export', state.query)
    .then(() => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}
// 所有流程
const allProcessesArr = ref([])
// 查询所有流程
const getAllProcesses = () => {
  apiQueryAllProcesses().then((res) => {
    if (res.data.success === true) {
      allProcessesArr.value = res.data.data || []
    }
  })
}
// 所有任务名称
const allTaskArr = ref([])
// 查询所有流程
const getAllTask = () => {
  apiQueryTask().then((res) => {
    if (res.data.success === true) {
      allTaskArr.value = res.data.data || []
    }
  })
}
// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}
// 流程发起部门
const allDeptArr = ref([])
// 查询所有流程发起部门
const getAllProcessesDept = () => {
  apiQueryDept().then((res) => {
    if (res.data.success === true) {
      allDeptArr.value = res.data.data || []
    }
  })
}

// 发起系统
const allStartAppArr = ref([])
// 查询发起系统
const getAllStartApp = () => {
  apiQueryApp().then((res) => {
    if (res.data.success === true) {
      allStartAppArr.value = res.data.data.result || []
    }
  })
}
onMounted(() => {
  getAllProcesses()
  getAllTask()
  getAllProcessesStarter()
  getAllProcessesDept()
  getAllStartApp()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
